# -*- coding: utf-8 -*-
from .models import User


def jwt_response_payload_handler(token, user=None, request=None, role=None):
    """
    自定义jwt认证成功返回数据
    :token  返回的jwt
    :user   当前登录的用户信息[对象]
    :request 当前本次客户端提交过来的数据
    :role 角色
    """
    if user.first_name:
        name = user.first_name
    else:
        name = user.username

    return {
        'authenticated': 'true',
        'is_superuser': user.is_superuser,
        'id': user.id,
        "role": role,
        'name': name,
        'username': user.username,
        'email': user.email,
        'token': token,
    }


# 以前使用username进行用户验证，现在修改成email进行验证

class EmailAuthBackend:
    def authenticate(self, request, username=None, password=None):
        '''
        request: request请求对象
        username:  用户名&邮箱&手机号
        password: 密码
        '''
        try:  # 通过用户名获取
            user = User.objects.get(username=username)
        except Exception as e:
            user = None
        if not user:
            try:
                user = User.objects.get(email=username)
            except Exception as e:
                user = None
        if user and user.check_password(password):
            return user
        else:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
